/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "i2c_mux.h"
#include <mc/exception.h>
#include <mc/log.h>

using namespace dev;

bool i2c_mux_object::init(mc::mutable_dict& csr_object, const mc::dict& connector) {
    try {
        // 验证参数
        if (csr_object.empty()) {
            MC_THROW(mc::invalid_op_exception, "csr_object is empty");
        }

        // 获取并设置I2C总线内部对象
        auto& manager = dev::device_manager::get_instance();
        auto  bus_variant =
            manager.find_object(csr_object["object_name"].as<std::string>(), dev::object_type::bus);
        if (std::holds_alternative<std::shared_ptr<bus_base>>(bus_variant)) {
            auto bus_ptr = std::get<std::shared_ptr<bus_base>>(bus_variant);
            if (bus_ptr) {
                m_interface_i2c_mux.m_bus = static_cast<dev::bus_base*>(bus_ptr.get());
                m_interface_i2c_mux.from_variant(csr_object);
            } else {
                MC_THROW(mc::invalid_op_exception, "I2C MUX bus not found, name: ${name}",
                         ("name", csr_object["object_name"].as<std::string>()));
            }
        } else {
            MC_THROW(mc::invalid_op_exception, "I2C MUX bus not found, name: ${name}",
                     ("name", csr_object["object_name"].as<std::string>()));
        }
    } catch (const std::exception& e) {
        elog("I2C MUX initialization exception: ${exception}", ("exception", e.what()));
        return false;
    }

    return true;
}

uint8_t i2c_mux_object::get_id() {
    return this->m_interface_i2c_mux.ChannelId;
}

MC_REFLECT(dev::i2c_mux_object, ((m_interface_i2c_mux, "bmc.dev.Bus.I2cMux")))
